<?php
/**
 * 缓存管理
 * @author zhu
 *
 */
namespace App\CLI;

use Forxx\console\CLIRunner;
use Forxx\console\CConsole;
use Forxx\RedisCache;

class CCache  extends CLIRunner{

    public function redis_action()
    {
        $key = CConsole::prompt("input the cache key .(`*` for all)","*");
//        $cacheKeysClass = new \ReflectionClass('\Forxx\CacheKeys');
//        $keys = $cacheKeysClass->getConstants();
        $keys = RedisCache::instance()->keys('*');
        $pattern = "/^".str_replace("*",".*",$key)."$/";
        $matches = [];
        foreach($keys as $cacheKey)
        {
            $ret = preg_match($pattern,$cacheKey);
            if($ret !== false && $ret>0)
            {
                $matches[] = $cacheKey;
            }
        }
        if(count($matches) > 0)
        {
            CConsole::print_line("delete all under key !");
            CConsole::print_line("\t".implode("\n\t",$matches));
            if(CConsole::confirm("are your sure ?",true))
            {
                self::deleteRedis($matches);
            }
        }
        else
        {
            CConsole::print_line("no key matched by '{$key}'");
        }
    }

    protected static function deleteRedis($key)
    {
        $keys = [];
        if(is_array($key))
        {
            $keys = $key;
        }
        elseif(is_string($key))
        {
            $keys[] = $key;
        }

        foreach($keys as $k)
        {
            RedisCache::instance()->delete($k);
            CConsole::print_line("delete cache of {$k}");
        }
    }

    public function  publish_action(){
        $token = "CC1B078EF7F9F78F8166BF78F6A95EF6";
        $key = "sse_".$token;
        $data = json_encode([
            'command' => 'ask',
            'time' => time(),
            //'args' => null,
        ],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        return RedisCache::instance()->rpush($key,$data);
    }

    public function consume_action(){
        $start = time();
        $resp = [];
        $key = "sse_CC1B078EF7F9F78F8166BF78F6A95EF6";
        while(true){
            $tn = time();
            if($tn - $start > 1800){ // 半小时 重置一次
                break;
            }
            $data = RedisCache::instance()->lpop($key);
            if(!empty($data)){
                $resp = @json_decode($data,true);
                break;
                //echo "data: ".$data."\n\n";
            }
            else{
                echo "no data for ".$key."\n";
                sleep(1);
            }
        }
        return $resp;
    }

}